import java.util.Arrays;

/**
 * @ClassName LC34
 * @Author ykx
 * @Date 2024/3/14 11:54
 * @Version 1.0
 */
public class LC34 {
    public static void main(String[] args) {
        int[] nums = new int[]{1, 1, 2};
        int target = 1;
        LC34 lc34 = new LC34();
        System.out.println(Arrays.toString(lc34.searchRange(nums, target)));
    }

    public int[] searchRange(int[] nums, int target) {
        int[] result = new int[]{-1, -1};
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                // 中间值就是目标元素，将索引赋值给第一个结果，分别左右遍历到最后一个不等于目标元素的索引
                int start = mid, end = mid;
                while (start >= 0 && nums[start] == nums[mid]) {
                    start--;
                }
                while (end <= nums.length - 1 && nums[end] == nums[mid]) {
                    end++;
                }

                result[0] = start + 1;
                result[1] = end - 1;

                return result;
            } else if (nums[mid] < target) {
                // 中间值比目标元素小，左指针移动到中点的前一位
                left = mid + 1;
            } else if (nums[mid] > target) {
                // 中间值比目标元素大，右指针移动到中点的前一位
                right = mid - 1;
            }
        }
        return result;
    }
}
